package com.crazy.web.controller.share;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ValidateException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.crazy.enums.Constants;
import com.crazy.model.major.entity.TArticle;
import com.crazy.model.major.entity.TSurvey;
import com.crazy.model.major.entity.TSurveyTime;
import com.crazy.model.major.service.TSurveyService;
import com.crazy.model.major.service.TSurveyTimeService;
import com.crazy.rest.RestResult;
import com.crazy.web.controller.BaseController;
import com.crazy.web.service.outer.SurveyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Controller
@RequestMapping("/share/survey")
public class SurveyController extends BaseController {

    @Autowired
    private SurveyService surveyService;
    @Autowired
    private TSurveyTimeService tSurveyTimeService;

    /**
     * 打开问卷列表页
     * @return
     */
    @RequiresPermissions("survey:view")
    @GetMapping("/view")
    public String view() {
        QueryWrapper<TSurveyTime> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(TSurveyTime.Columns.id);
        List<TSurveyTime> surveyTimes = tSurveyTimeService.list(queryWrapper);
        if(surveyTimes!=null && !surveyTimes.isEmpty()){
            request.setAttribute("startTime", DateUtil.format(surveyTimes.get(0).getStartTime(),"yyyy/MM/dd HH:mm"));
            request.setAttribute("endTime", DateUtil.format(surveyTimes.get(0).getEndTime(),"yyyy/MM/dd HH:mm"));
        }
        request.setAttribute("url", "/share/survey/view");
        return "survey/view";
    }

    @ResponseBody
    @RequiresPermissions("survey:list")
    @GetMapping("/list")
    public RestResult list(@RequestParam int page, @RequestParam int rows, @RequestParam(required = false) String search) {
        IPage<TSurvey> surveyIPage = surveyService.list(page, rows, search);
        return RestResult.createSuccessResult("查询成功", surveyIPage);
    }

    @ResponseBody
    @RequiresPermissions("survey:time")
    @GetMapping("/time")
    public RestResult time(@RequestParam String startTime, @RequestParam String endTime) {
        TSurveyTime surveyTime = new TSurveyTime();
        surveyTime.setStartTime(DateUtil.parseLocalDateTime(startTime, "yyyy-MM-dd HH:mm"));
        surveyTime.setEndTime(DateUtil.parseLocalDateTime(endTime, "yyyy-MM-dd HH:mm"));
        surveyService.saveSurveyTime(surveyTime);
        return RestResult.createSuccessResult("设置成功");
    }

}
